package com.wnzt.baszh.util.common;

import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.PageRanges;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.tools.PrintPDF;
import org.apache.xml.security.utils.Base64;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class PrintUtils {
	
	public static void main(String[] args) {
		String pdfFilePath="F:\\new.pdf";
		try {
			compose("E:\\pdf2",pdfFilePath);
			long a=System.currentTimeMillis();
			printWithDialog(pdfFilePath);
			System.out.println("执行耗时 : "+(System.currentTimeMillis()-a)/1000f+" 秒 ");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		
		 try {
			long a=System.currentTimeMillis();
			PrintPDF.main(new String[]{
				       "-silentPrint",//静默打印
				       "-printerName","Microsoft XPS Document Writer" ,//指定打印机名
				       "-orientation","auto",//打印方向，三种可选auto|landscape|portrait
				       pdfFilePath//"pdfFilePath"//打印PDF文档的路径
				    });
			System.out.println("执行耗时 : "+(System.currentTimeMillis()-a)/1000f+" 秒 ");
		} catch (PrinterException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 文件夹下pdf文件合成
	 * @param folderPath pdf文件夹
	 * @param newFile	 新文件
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static void compose(String folderPath,String newFile) throws IOException, DocumentException{
		
		FileOutputStream out = new FileOutputStream(newFile);

	    Document document = new Document();
	    PdfWriter writer = PdfWriter.getInstance(document, out);

	    document.open();
	    PdfContentByte cb = writer.getDirectContent();

	    int totalPages = 0;

	    List<PdfReader> readers = new ArrayList<PdfReader>();
	    
	    List<File> filelist=new ArrayList<File>();
		filelist=getFileList(filelist,folderPath);
		for (File file : filelist) {
			PdfReader reader = new PdfReader(file.getPath()); 
			totalPages += reader.getNumberOfPages();
			readers.add(reader);
		}

	    int pageOfCurrentReaderPDF = 0;
	    Iterator<PdfReader> iteratorPDFReader = readers.iterator();

	    while (iteratorPDFReader.hasNext()) {
	        PdfReader pdfReader = iteratorPDFReader.next();

	        while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
	            document.newPage();
	            pageOfCurrentReaderPDF++;
	            PdfImportedPage page = writer.getImportedPage(pdfReader,
	                    pageOfCurrentReaderPDF);
	            cb.addTemplate(page, 0, 0);
	        }
	        pageOfCurrentReaderPDF = 0;
	    }
	    out.flush();
	    document.close();
	    out.close();
	    
	}
	
    public static void printWithDialog(String filePath) {
        try {
            PDDocument document = PDDocument.load(new File(filePath));
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPageable(new PDFPageable(document));
            if (job.printDialog()){
            	System.out.println("打印开始.");
                job.print();
                System.out.println("打印结束.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }

    public static String getFilePath(String fileName){
        File path = new File(System.getProperty("user.dir").concat("/downFile"));
        if (!path.exists() && !path.isDirectory()) {
            path.mkdir();
        }
        String filePath = path + "/" + fileName;
        return filePath;
    }

    public static boolean downloadFile(String fileURL,String fileName) {
        try {
            URL url = new URL(fileURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            DataInputStream in = new DataInputStream(connection.getInputStream());
            DataOutputStream out = new DataOutputStream(new FileOutputStream(getFilePath(fileName)));
            byte[] buffer = new byte[4096];
            int count = 0;
            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
            out.close();
            in.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    public static void printFile(String path) throws Exception {
        File file = new File(path);
        File[] fies=file.listFiles();
            for(File f:fies){
            System.out.println("file "+f.getName());
                 String fileExt=f.getName().substring(f.getName().indexOf(".")+1,f.getName().length());
                  if("pdf".equalsIgnoreCase(fileExt)){
                    String filepath=path+File.separator+f.getName();
                    File pdfFile=new File(filepath);
                    //构建打印请求属性集
                    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
                    //设置打印格式，因为未确定文件类型，这里选择AUTOSENSE
                    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
                    //查找所有的可用打印服务
                    PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
                    //定位默认的打印服务
                    PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
                     //显示打印对话框  
                    //PrintService service = ServiceUI.printDialog(null, 200, 200, printService,   defaultService, flavor, pras);
                    if(defaultService!=null){
                        DocPrintJob job = defaultService.createPrintJob(); //创建打印作业
                        FileInputStream fis = new FileInputStream(pdfFile); //构造待打印的文件流
                        DocAttributeSet das = new HashDocAttributeSet();
                        Doc doc = new SimpleDoc(fis, flavor, das); //建立打印文件格式
                        job.print(doc, pras); //进行文件的打印
                }
                    f.delete();
            }
        }
      }
    
    public static List<File> getFileList(List<File> filelist,String strPath) {
        File dir = new File(strPath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();
                if (files[i].isDirectory()) { // 判断是文件还是文件夹
                    getFileList(filelist,files[i].getAbsolutePath()); // 获取文件绝对路径
                } else if (fileName.endsWith("pdf")) { // 判断文件名是否以.avi结尾
                    String strFileName = files[i].getAbsolutePath();
                    System.out.println("---" + strFileName);
                    filelist.add(files[i]);
                } else {
                    continue;
                }
            }

        }
        return filelist;
    }
}
